<template>
  <el-upload class="upload-demo" drag accept=".txt" :multiple="true" :show-file-list="false"
    :http-request="uploadFile">
    <i class="el-icon-upload"></i>
    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
    <div class="el-upload__tip" slot="tip">只能上传txt文件，且不超过50MB</div>
  </el-upload>
</template>

<script>
import { upload } from "@/api/upload";

export default {
  methods: {
    uploadFile(item) {
      this.$message({"message":"上传文件并解析中，请稍后！", duration: 0});
      let timestamp = new Date().getTime();
      let formData = new FormData();
      formData.append("file", item.file);
      formData.append("time", timestamp);
      upload(formData)
        .then((res) => {
          this.$message.closeAll();
          this.$message.success("解析成功，开始下载");
          let filename = item.file.name;
          filename = filename.replace(".txt", "_out.txt");
          const a = document.createElement("a");
          const url = "/api/md5/download?time=" + timestamp + "&filename=" + filename;
          a.setAttribute("href", url);
          a.setAttribute("download", filename);
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
        }).catch((err) => {
          this.$message.error(err.message);
        })
    }
  }
}
</script>

<style scoped>
.upload-demo {
  text-align: center;
  padding-top: 30px;
}
</style>
